package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.LinearInterpolator;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.PriAudioAdapter;
import flc.ast.adapter.SelPictureItemAdapter;
import flc.ast.bean.MyAudioBean;
import flc.ast.bean.MyImgItemBean;
import flc.ast.bean.MyPicAlbumBean;
import flc.ast.bean.MyVideoBean;
import flc.ast.databinding.ActivityPrivacyFileBinding;
import flc.ast.dialog.AudioEditDialog;
import flc.ast.dialog.InfoDialog;
import flc.ast.dialog.RenameDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.audio.AudioPlayerImpl;
import stark.common.basic.media.audio.IAudioPlayer;
import stark.common.basic.media.bean.AudioBean;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.SPUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.TimeUtil;

public class PrivacyFileActivity extends BaseAc<ActivityPrivacyFileBinding> implements IAudioPlayer.IListener {

    private List<MyPicAlbumBean> listPicture = new ArrayList<>();
    private List<MyAudioBean> listAudio = new ArrayList<>();
    private SelPictureItemAdapter selPictureItemAdapter;
    private PriAudioAdapter audioAdapter;
    //是否开启隐蔽模式
    private boolean isHideMode;
    private int selPosition;
    protected IAudioPlayer mAudioPlayer;
    private ObjectAnimator mRotaAnimator;

    @Override
    protected int onCreate() {
        return R.layout.activity_privacy_file;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivPrivacyFileBack.setOnClickListener(v -> onBackPressed());

        mAudioPlayer = new AudioPlayerImpl();
        mAudioPlayer.setListener(this);

        mDataBinding.tvPicture.setOnClickListener(this);
        mDataBinding.tvAudio.setOnClickListener(this);
        mDataBinding.ivPlay.setOnClickListener(this);

        mDataBinding.rvFileList.setLayoutManager(new LinearLayoutManager(mContext));
        selPictureItemAdapter = new SelPictureItemAdapter();
        selPictureItemAdapter.addChildClickViewIds(R.id.rlSelPicture1, R.id.rlSelPicture2, R.id.rlSelPicture3, R.id.rlSelPicture4, R.id.rlSelPicture5, R.id.rlSelPicture6);
        selPictureItemAdapter.setOnItemChildClickListener(this);
        audioAdapter = new PriAudioAdapter();
        audioAdapter.addChildClickViewIds(R.id.ivSelAudioItemEdit);
        audioAdapter.setOnItemChildClickListener(this);
        audioAdapter.setOnItemClickListener(this);
        mDataBinding.rvFileList.setAdapter(selPictureItemAdapter);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvPicture://图片
                clearSelection();
                mDataBinding.tvPicture.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvPicture.setTextSize(24);
                mDataBinding.ivPicture.setVisibility(View.VISIBLE);
                getPictureData();
                mDataBinding.rvFileList.setAdapter(selPictureItemAdapter);
                mAudioPlayer.pause();
                mRotaAnimator.cancel();
                mDataBinding.llPlay.setVisibility(View.GONE);
                break;
            case R.id.tvAudio://音频
                clearSelection();
                mDataBinding.tvAudio.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvAudio.setTextSize(24);
                mDataBinding.ivAudio.setVisibility(View.VISIBLE);
                getAudioData();
                mDataBinding.rvFileList.setAdapter(audioAdapter);
                break;
            case R.id.ivPlay://播放
                if (mAudioPlayer.isPlaying()) {
                    mAudioPlayer.pause();
                } else {
                    mAudioPlayer.resume();
                }
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        audioAdapter.getItem(selPosition).setSelected(false);
        audioAdapter.notifyItemChanged(selPosition);
        selPosition = position;
        audioAdapter.getItem(position).setSelected(true);
        audioAdapter.notifyItemChanged(position);
        mAudioPlayer.play(audioAdapter.getItem(position).getPath());
        setPlayData();
        mDataBinding.llPlay.setVisibility(View.VISIBLE);
        mRotaAnimator.start();
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        if (adapter == selPictureItemAdapter) {
            MyPicAlbumBean item = (MyPicAlbumBean) adapter.getItem(position);
            switch (view.getId()) {
                case R.id.rlSelPicture1://top图片1
                    toDetail(item.getList().get(0));
                    break;
                case R.id.rlSelPicture2://top图片2
                    toDetail(item.getList().get(1));
                    break;
                case R.id.rlSelPicture3://top图片3
                    toDetail(item.getList().get(2));
                    break;
                case R.id.rlSelPicture4://top图片4
                    toDetail(item.getList().get(3));
                    break;
                case R.id.rlSelPicture5://top图片5
                    toDetail(item.getList().get(4));
                    break;
                case R.id.rlSelPicture6://top图片6
                    toDetail(item.getList().get(5));
                    break;
            }
        } else if (adapter == audioAdapter) {
            switch (view.getId()) {
                case R.id.ivSelAudioItemEdit://编辑
                    showEditDialog(position);
                    break;
            }
        }
    }

    @Override
    protected void initData() {
        //是否开启隐蔽模式
        isHideMode = SPUtil.getBoolean(mContext, Content.isHideMode, false);
        if (isHideMode) {
            mDataBinding.rvFileList.setVisibility(View.GONE);
            mDataBinding.tvFileNoData.setVisibility(View.VISIBLE);
        } else {
            getPictureData();
        }
        initAnimator();
    }

    private void initAnimator() {
        mRotaAnimator = ObjectAnimator.ofFloat(mDataBinding.ivPlayIcon, "rotation", 0f, 360f);
        mRotaAnimator.setRepeatCount(ValueAnimator.INFINITE);
        mRotaAnimator.setInterpolator(new LinearInterpolator());//插值器实现匀速旋转
        mRotaAnimator.setDuration(3000);//时间
    }


    private void setPlayData() {
        mDataBinding.tvPlayName.setText(audioAdapter.getItem(selPosition).getName());
    }

    private void toDetail(MyImgItemBean item) {
        //去到图片详情
        PriPicDetailActivity.imgPath = item.getPath();
        startActivity(PriPicDetailActivity.class);
    }

    private void getPictureData() {
        if (isHideMode) {
            mDataBinding.rvFileList.setVisibility(View.GONE);
            mDataBinding.tvFileNoData.setVisibility(View.VISIBLE);
            return;
        }
        listPicture.clear();
        List<MyImgItemBean> list = new ArrayList<>();
        //获取文件夹下文件
        String path = PathUtils.getFilesPathExternalFirst() + Content.myPrivacyFile;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                if (ImageUtils.isImage(file)) {
                    list.add(new MyImgItemBean(file.getPath(), false));
                }
            }
        }
        if (list.size() > 0) {
            // 使用流操作将数据按每 6 条一组进行分组
            Map<Integer, List<MyImgItemBean>> groups = new HashMap<>();
            int groupSize = 6;
            for (int i = 0; i < list.size(); i += groupSize) {
                if ((i + groupSize) <= list.size()) {
                    groups.put((i / groupSize), list.subList(i, i + groupSize));
                } else {
                    groups.put((i / groupSize), list.subList(i, list.size()));
                }
            }
            for (Map.Entry<Integer, List<MyImgItemBean>> entry : groups.entrySet()) {
                listPicture.add(new MyPicAlbumBean(entry.getValue()));
            }
            selPictureItemAdapter.setList(listPicture);
            mDataBinding.rvFileList.setVisibility(View.VISIBLE);
            mDataBinding.tvFileNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvFileList.setVisibility(View.GONE);
            mDataBinding.tvFileNoData.setVisibility(View.VISIBLE);
        }
    }

    private void getAudioData() {
        if (isHideMode) {
            mDataBinding.rvFileList.setVisibility(View.GONE);
            mDataBinding.tvFileNoData.setVisibility(View.VISIBLE);
            return;
        }
        listAudio.clear();
        //获取文件夹下文件
        String path = PathUtils.getFilesPathExternalFirst() + Content.myPrivacyFile;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                if (!ImageUtils.isImage(file)) {
                    listAudio.add(new MyAudioBean(file.getPath(), file.getName(), MediaUtil.getDuration(file.getPath()), file.length()));
                }
            }
        }
        if (listAudio.size() > 0) {
            audioAdapter.setList(listAudio);
            mDataBinding.rvFileList.setVisibility(View.VISIBLE);
            mDataBinding.tvFileNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvFileList.setVisibility(View.GONE);
            mDataBinding.tvFileNoData.setVisibility(View.VISIBLE);
        }
    }

    private void clearSelection() {
        mDataBinding.tvPicture.setTextColor(Color.parseColor("#80FFFFFF"));
        mDataBinding.tvPicture.setTextSize(15);
        mDataBinding.ivPicture.setVisibility(View.GONE);
        mDataBinding.tvAudio.setTextColor(Color.parseColor("#80FFFFFF"));
        mDataBinding.tvAudio.setTextSize(15);
        mDataBinding.ivAudio.setVisibility(View.GONE);
    }

    private void showEditDialog(int position) {
        AudioEditDialog dialog = new AudioEditDialog(mContext);
        dialog.hint = getString(R.string.move_privacy_file);
        dialog.audioPath = listAudio.get(position).getPath();
        dialog.setListener(new AudioEditDialog.Ilistener() {
            @Override
            public void clickRename() {
                showRenameDialog(position);
            }

            @Override
            public void clickShare() {
                IntentUtil.shareVideo(mContext, listAudio.get(position).getPath());
            }

            @Override
            public void clickAddPrivacyFolder() {
                delete(position);
            }

            @Override
            public void clickInfo() {
                showInfoDialog(position);
            }

            @Override
            public void clickDelete() {
                delete(position);
            }
        });
        dialog.show();
    }

    private void showRenameDialog(int position) {
        RenameDialog dialog = new RenameDialog(mContext);
        dialog.title = getString(R.string.file_rename);
        dialog.hint = getString(R.string.please_input_folder_name_text);
        dialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                FileUtils.rename(listAudio.get(position).getPath(), name + "." + FileUtils.getFileExtension(listAudio.get(position).getPath()));
                getAudioData();
            }
        });
        dialog.show();
    }

    private void delete(int position) {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //从此文件夹删除
                        mContext.getContentResolver().delete(UriUtils.res2Uri(listAudio.get(position).getPath()), null, null);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        getAudioData();
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }

    private void showInfoDialog(int position) {
        InfoDialog dialog = new InfoDialog(mContext);
        dialog.videoPath = listAudio.get(position).getPath();
        dialog.show();

    }

    @Override
    public void onUpdatePlayTime(int curPlayTime, int duration) {
        mDataBinding.tvPlayTime.setText(TimeUtil.getMmss(curPlayTime) + "/" + TimeUtil.getMmss(duration));
        if (curPlayTime >= duration) {
            mDataBinding.llPlay.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPlayChange(boolean isPlaying) {
        if (isPlaying) {
            mDataBinding.ivPlay.setImageResource(R.drawable.azantin);
            mRotaAnimator.start();
        } else {
            mDataBinding.ivPlay.setImageResource(R.drawable.abof);
            mRotaAnimator.cancel();
        }
    }
}